package nsn.message.aggragtor.feeds;


import java.net.URL;
import java.util.List;

import nsn.message.aggragtor.feeds.exceptions.EntryFeedException;
import nsn.message.aggregator.model.IEntry;
import nsn.message.aggregator.model.Source;

import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;

/**
 * 
 * 
 * @author Lukasz Nowak
 * @since 10-03-2011
 * 
 */
public class SourceFeed extends Source {

	/**
     * 
     */
	private static final long serialVersionUID = 4251157544613375554L;
	private SyndFeed _syndFeed;
	private final URL _url;



	/**
	 * 
	 * 
	 * @param sourceType
	 * @param url
	 */
	protected SourceFeed(final SourceTypeFeed sourceType, final URL url) {
		_url = url;
		setType(sourceType);
		setName(getSyndFeed().getTitle());

	}

	@Override
	public void update() {
		try {
			final SourceTypeFeed type = (SourceTypeFeed) getType();
			_syndFeed = type.getFeedFetcher().retrieveFeed(_url);

			final List<?> feedEntries = getSyndFeed().getEntries();
			for (final Object obj : feedEntries) {
				if (obj instanceof SyndEntry) {
					final SyndEntry syndEntry = (SyndEntry) obj;
					final IEntry entry = new EntryFeed(this, syndEntry);
					if (!getEntries().contains(entry)) {
						getEntries().add(entry);
					}
				}
			}
			
			type.fireChangeEvent("SourceUpdated", null, this);

		} catch (final Exception e) {
			throw new EntryFeedException(e);
		}
	}

	@Override
	public void delete() {
		final SourceTypeFeed type = (SourceTypeFeed) getType();
		type.delete(this);
	}


	
	private SyndFeed getSyndFeed() {
		if (_syndFeed == null) {
			update();
		}
		return _syndFeed;
	}
}
